package com.zerox.service.impl;

import com.zerox.entity.SysUser;
import com.zerox.mapper.SysUserMapper;
import com.zerox.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

@Service
public class SysUserServiceImpl implements SysUserService {


    @Autowired
    private SysUserMapper sysUserMapper;




    @Override
    public List<SysUser> list() {
        return sysUserMapper.list();
    }

    @Override
    public SysUser login(String name,String password) {
        return sysUserMapper.login(name,password);
    }

    @Override
    public List<SysUser> listUser(Integer startIndex, Integer pageSize, String userName, Integer roleId) {
        if(Objects.isNull(startIndex)){
            startIndex = 1;
        }
        if(Objects.isNull(pageSize)){
            pageSize = 10;
        }
        int pageIndex = (startIndex-1)*pageSize;
        return sysUserMapper.listUser(pageIndex, pageSize, userName, roleId);
    }

    @Override
    public int count(String userName, Integer roleId) {
        return sysUserMapper.count(userName, roleId);
    }

    @Override
    public int add(SysUser sysUser) {
        if (sysUserMapper.add(sysUser) > 0) {
            List<SysUser> list = sysUserMapper.toSelectUserDesc();

            SysUser user = list.get(0);

            int userId = Math.toIntExact(user.getUserId());

            int roleId = Math.toIntExact(sysUser.getRoleId());

            if (sysUserMapper.toAddRole(userId, roleId) > 0) {
                return 1;
            }else {
                return 0;
            }
        }else {
            return 0;
        }
  }

    @Override
    public int toAddRole(Integer userId, Integer roleId) {
        return sysUserMapper.toAddRole(userId,roleId);
    }

    @Override
    public List<SysUser> toSelectUserDesc() {
        return sysUserMapper.toSelectUserDesc();
    }

//    @Override
//    public int addrelevancy() {
//        return sysUserMapper.addrelevancy();
//    }

    @Override
    public int delete(Integer id) {
        return sysUserMapper.delete(id);
    }

    @Override
    public SysUser userById(Integer id) {
        return sysUserMapper.userById(id);
    }

    @Override
    public int update(SysUser sysUser) {
        return sysUserMapper.update(sysUser);
    }

    @Override
    public int add2(SysUser sysUser) {
        return sysUserMapper.add2(sysUser);
    }


}
